/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.fyx.linker.controll;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.fyx.linker.entity.LinkerCategory;

/**
 *
 * @author xljan
 */
@Stateless
public class LinkerCategoryFacade extends AbstractFacade<LinkerCategory> 
implements LinkerCategoryFacadeLocal {
    @PersistenceContext(unitName = "FyxCorePU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public LinkerCategoryFacade() {
        super(LinkerCategory.class);
    }

    @Override
    public List<LinkerCategory> findByParent(LinkerCategory parent) {
        return em.createNamedQuery(LinkerCategory.NQ_FIND_BY_PARENT, 
                LinkerCategory.class).setParameter("parent", parent).
                getResultList();
    }

    @Override
    public LinkerCategory findRoot() {
        try {
            return em.createNamedQuery(LinkerCategory.NQ_FIND_ROOT, 
                    LinkerCategory.class).getSingleResult();
        } catch (NoResultException ex) {
            return null;
        }
    }

    @Override
    public void removeAll() {
        //TODO velmi vypocetne narocne, optimalizovat
        List<LinkerCategory> all = findAll();
        for (LinkerCategory linkerCategory : all) {
            linkerCategory.setParent(null);
        }
        em.flush();
        for (LinkerCategory linkerCategory : all) {
            remove(linkerCategory);
        }
        em.flush();
    }

    /**
     * Vrati kompletne naplnenou datovou strukturu od korene.
     * @return 
     */
    @Override
    public LinkerCategory getTree() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
